/**
 * Created by liguangsong on 16/8/15.
 */
$(document).ready(function() {
    $.get('/ajax_setShopping/', function(result){
        showShoppingCarList(result);
        bindCalcButtonClickEvent(result);
        bindInputKeyUp(result);
        bindInputNotNull(result);
        modifyTotalPrice();
        bindClickPayButton();
    })


});


function showShoppingCarList(goodInfo) {
    var data = {
        "shoppingCart": goodInfo
    };
    var template = $("#car_template").html();
    Mustache.parse(template);
    var shoppingCarInfo = Mustache.render(template, addCartDataId(data));
    $(".shop_cart thead").after(shoppingCarInfo);
}


function addCartDataId(data) {
    _.times(data.shoppingCart.length, function(index) {
        data.shoppingCart[index]["addId"] = "add" + data.shoppingCart[index].id;
        data.shoppingCart[index]["minId"] = "min" + data.shoppingCart[index].id;
        data.shoppingCart[index]["inputId"] = "input" + data.shoppingCart[index].id;
    });
    return data;
}

function runButtonAndInputEvent(id, number, goodInfo) {
    modifyInputAndSubtoalValue(id, number, goodInfo);
    modifyLocalData(id, number, goodInfo);

}

function bindCalcButtonClickEvent(goodInfo) {
    $("tr td div button").click(function () {
        var id = this.id.substring(3);
        var modifyNumber = getComputeNumber(id, this.innerHTML);
        runButtonAndInputEvent(id, modifyNumber, goodInfo);
    })
}

function getComputeNumber(id, mark) {
    var number = parseInt($("#" + id + " .input").val());
    if (mark == "-") {
        return number - 1;
    }
    if (mark == "+") {
        return number + 1;
    }
}

function searchSameGoodIndex(shopGood , id) {
    for (var i = 0; i < shopGood.length; i++) {
        if (shopGood[i]["id"] == id) {
            return i;
        }
    }
    return shopGood.length;
}



function modifyInputAndSubtoalValue(id, number, goodInfo) {
    var inputId = "#" + id + " .input";
    $(inputId).val(number);
    goodInfo = goodInfo[searchSameGoodIndex(goodInfo, id)];
    goodInfo["count"] = $(inputId).val();
    var subTotalPrice = getSubtotalPrice(goodInfo);
    $("#" + id + " .subtotal").text(subTotalPrice);
    if (goodInfo["count"] == 0) {
        $("#" + id).remove();
    }
}

function getTransInfo(good, number){
    dict = { 'type': good.type, 'name': good.name, 'unit': good.unit, 'discount': good.discount, 'price': good.price, 'change': true };
    dict.compute = number;
    return dict;
}

function modifyLocalData(id, number, goodInfo) {

    var index = searchSameGoodIndex(goodInfo, id);
    var good = goodInfo[index];
    good = getTransInfo(good, number);
    $.post('/ajax_setShopping/', good, function(result){
        console.log(result)
        modifyShopCarNumber();
        modifyTotalPrice();
    })   
}

function getSubtotalPrice(info) {
    var beforPrice = info["count"] * info["price"];
    if ( info["count"] > 2 && info["discount"]==true ) {
        var count = info["count"] - parseInt(info["count"] / 3);
        var realPrice = count * info["price"];
        return realPrice + "元(原价：" + beforPrice + "元)";
    }
    else {
        return beforPrice + "元";
    }
}



function modifyTotalPrice() {
    $.get('/ajax_setShopping/', function(goodInfo){
        var total = 0;
        _.times(goodInfo.length, function (i) {
            var index = goodInfo[i]["subtotal"].indexOf("元");
            var subTotal = goodInfo[i]["subtotal"].substring(0, index)
            total += parseFloat(subTotal);
        });
        $(".pay_div p b").text(total.toFixed(2) + '元');
    })


}


function bindInputKeyUp(goodInfo) {
    $("input").keyup(function() {
        var text = $(this).val();
        if (isNaN(text) || text == " " ) {
            $(this).val("1");
        }
        if (text != "") {
            var id = this.id.substring(5);
            var modifyNumber = parseInt($(this).val());
            runButtonAndInputEvent(id, modifyNumber, goodInfo);
        }
    });
}

function bindInputNotNull(goodInfo) {
    $("input").change(function() {
        var text = $(this).val();
        var id = this.id.substring(5);
        if (text == "") {
            runButtonAndInputEvent(id, 1, goodInfo);
        }
    })
}

function bindClickPayButton() {
    $(".pay_div button").click(function () {
        window.location.href = "/pay/";
    })
}



